<template>
  <div class="app-container">
    <div v-if="showSearch" class="search-container">
      <CommonSearch
        :formConfig="searchColumns"
        :inline="true"
        labelWidth="auto"
        formItemWidth="auto"
        :model="searchParam"
      >
        <template #after>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </template>
      </CommonSearch>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="ids.length === 0"
          @click="handleTableDelete()"
        >
          <i-ep-delete />
          删除
        </el-button>
      </template>
      <!-- 表格主体 -->
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        v-bind="$attrs"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <el-table-column type="selection" width="55" align="center" />

        <!-- 表格内容操作 -->
        <template v-for="item in tableColumns" :key="item">
          <TableColumn v-if="item.prop && item.isShow" :column="item">
            <template v-for="slot in Object.keys($slots)" #[slot]="scope">
              <slot :name="slot" v-bind="scope"></slot>
            </template>
          </TableColumn>
        </template>

        <el-table-column fixed="right" label="操作" width="200" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleTableDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <add-table
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="reset"
      @change-visible="changeVisible"
    />

    <!-- 列设置 抽屉组件 -->
    <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e:boolean) => (showSearch = e)"
    />
  </div>
</template>

<script setup lang="tsx">
import { useTable, useDictionary } from "@/utils/useTable";
import { filterOrder } from "@/utils/commonHooks";
defineOptions({
  name: "SYSTEMTABLE",
  inheritAttrs: false,
});

/** 自定义设置方法   start **/

// 搜索参数 设置为响应式
const searchColumns: any = reactive([
  {
    type: "input", // 普通输入框
    isShow: true,
    inputType: "text", // 类型, text/textarea
    label: "角色名称", // 标签文本
    fieldName: "roleName", // 字段名称
    placeholder: "请输入角色名称", // 提示文字
    initValue: "", // 默认值
  },
  {
    type: "select",
    label: "读取列表",
    isShow: true,
    fieldName: "type",
    placeholder: "请选择类型",
    initValue: null,
    defaultFirstOption: true,
    optionList: useDictionary("LogLevel"),
  },
]);

// 接收 columns 并设置为响应式
const tableColumns = reactive([
  {
    prop: "roleName",
    label: "用户姓名",
    render: (scope: any) => (
      <el-button
        type="primary"
        link
        onClick={() => ElMessage.success("我是通过 tsx 语法渲染的内容")}
      >
        {scope.row.roleName}
      </el-button>
    ),
  },
  { prop: "id", label: "角色ID", isShow: true },
  {
    prop: "roleName1",
    label: "多级表格",
    isShow: true,
    _children: [
      { prop: "createTime", label: "用户姓名", width: 110, isShow: true },
      { prop: "ids", label: "年龄", width: 100, isShow: true },
      {
        prop: "enableds",
        label: "性别",
        width: 100,
        enum: useDictionary("Enabled"),
        fieldNames: { label: "genderLabel", value: "genderValue" },
      },
      {
        prop: "enabledLabel",
        label: "详细资料",
        _children: [
          { prop: "version", label: "身份证号" },
          { prop: "email", label: "邮箱" },
          { prop: "address", label: "居住地址" },
        ],
      },
    ],
  },
  { prop: "remarks", label: "备注", width: "auto", isShow: true },
  {
    prop: "enabled",
    label: "状态",
    width: 120,
    sortable: true,
    isShow: true,
    render: (scope: any) => (
      <el-tag>{useDictionary("Enabled", scope.row.enabled)}</el-tag>
    ),
  },
]);

// 是否显示搜索框
const showSearch = ref(true);

/** 列表项自定义方法   end **/

// 请求参数
const requestApi = "/system/sysRole/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({ sort: {} });

// 初始化搜索参数数据
const searchParamInit = {
  roleName: "",
  type: "",
};

const deleteParam = {
  api: "/system/sysRole/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

// 数据请求错误后处理
// function dataCallBack() {}   //需要处理
const dataCallBack = ref(undefined); //无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 如果初始化表格需要排序=》const initParam = reactive({sort:''});
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });
onMounted(async () => {
  getTableList();
});

// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}

/** 打开角色表单弹窗 */
const addDialog = reactive<DialogOption>({
  visible: false,
  title: "",
  data: {},
});

const classData = {
  id: "jeffjeffjeffjeffjeffjeff",
  className: "hahaha",
  classPerson: "asdcasd",
  classTeacher: "jeff",
  classId: "jeffjeff",
  studentData: [
    {
      id: "111",
      sex: "1",
      name: "haha",
      isLive: false,
      phone: "17600002036",
    },
    {
      id: "222",
      sex: "2",
      name: "haha8989",
      isLive: true,
      phone: "17600602036",
    },
  ],
};

function openDialog(roleObj?: Object) {
  addDialog.visible = true;
  if (roleObj) {
    addDialog.title = "修改角色";
    addDialog.data = classData;
    console.log("修改角色", addDialog.data);
  } else {
    addDialog.title = "新增角色";
  }
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
}
</script>
